package fr;

import javax.servlet.http.HttpServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Field;




public class ControlServlet extends  HttpServlet {



	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {resp.setContentType( "text/html" );
			doPost(request,resp);



	}

	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {

		String login = request.getParameter("login");
		String motdepasse = request.getParameter("motdepasse");
		InetAddress  Ip = (InetAddress) request.getAttribute("IP");
		String ipAddress = (String)request.getAttribute("monIp");
		PrintWriter out = resp.getWriter();
		Controle cs = new Controle();

//== comparaison du login et mdp + récupération du login afin de l'afficher ds une page jsp
		
		
		
		Connection dm= (Connection)request.getServletContext().getAttribute("cnx");
		Statement s = null;
		try {
			s = dm.createStatement();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block !
			e1.printStackTrace();
		}

		ResultSet r = null;
		
		String req = "select * from identification where Login='"+login+"' AND Mdp='"+motdepasse+"'";
		
		System.out.println(req);
		
		
		try {
			r = s.executeQuery(req);
			
			
			if(r.first()) {
				request.getSession().setAttribute("log", login);
				resp.sendRedirect("Identification.jsp");
//			out.print("<html>");
//			out.println( "<body>" );
//			out.println( "<h4>Utilisateur connecté avec succés</h4>");
//			out.println( "</body></html>" );
			}
			
			
			else {
				resp.sendRedirect("http://www.google.fr");

		}

			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
//
//		int  i= 0;
//		i=cs.test(login, motdepasse);
//		if (i==1) {
//			out.print("<html>");
//			out.println( "<body>" );
//			out.println( "<h4>Utilisateur connecté avec succés</h4>" + ipAddress +Ip);
//			out.println( "</body></html>" );
//		}
		
		//=== Récupération de l'objet connexion

		ServletContext cn =getServletContext();
		System.out.println(cn.getAttribute("cnx"));






	}

}
